import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_im_demo/model/chat_model.dart';
import 'package:flutter_im_demo/model/message_model.dart';
import 'package:flutter_im_demo/state/global_state.dart';
import 'package:flutter_im_demo/widget/loading_widget.dart';
import 'package:flutter_im_demo/widget/navigation_widget.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:provider/provider.dart';

import '../const_value.dart';
import 'chat_page.dart';
import 'friend_list_page.dart';

class ChatListPage extends StatelessWidget {
  const ChatListPage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text(appTitle),
        flexibleSpace: Container(
          decoration: BoxDecoration(gradient: gradientColor),
        ),
        actions: <Widget>[
          IconNumWidget(icon: Icon(FontAwesomeIcons.bell, size: iconSize + 1)),
        ],
      ),
      body: Consumer<GlobalState>(
        builder: (context, state, _) {
          return state.isLogin != null && state.isLogin
              ? (state.isLoading ? const LoadingWidget() : ChatListWidget())
              : const NavigationWidget();
        },
      ),
    );
  }
}

class IconNumWidget extends StatelessWidget {
  final Icon icon;

  const IconNumWidget({this.icon, Key key}) : super(key: key);

  final width = 8.0;

  @override
  Widget build(BuildContext context) {

    return Consumer<GlobalState>(builder: (context, state, _) {
      print("state.addFriendMessage: ${state.addFriendMessage}");
      return Offstage(
        offstage: !state.isLoading && !state.isLogin,
        child: IconButton(icon: Stack(
          alignment: Alignment.topRight,
          children: <Widget>[
            icon,
            Offstage(
              offstage: !state.addFriendMessage,
              child: Container(
                width: width,
                height: width,
                decoration: BoxDecoration(
                  color: Colors.red,
                  borderRadius: BorderRadius.circular(width / 2),
                ),
              ),
            ),
          ],
        ), onPressed: (){
          state.updateAddFriendMessageFlag(false);
          Navigator.of(context).pushNamed("addList");
        }),
      );
    });
  }
}

class ChatListWidget extends StatelessWidget {
  const ChatListWidget({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer<GlobalState>(
      builder: (context, state, _) {
        return ListView.builder(
          padding: EdgeInsets.only(top: 8.0),
          itemBuilder: (context, index) {
            final chatModel = state.getChatModel(index);
            return ChatItemWidget(
              chatModel: chatModel,
              key: Key(chatModel.friend.id),
              onTap: () {
                toChatPageInitState(state, chatModel.friend);
                Navigator.of(context)
                    .push(MaterialPageRoute(builder: (context) {
                  return ChatPage(
                      friend: chatModel.friend, myId: state.userInfoModel.id);
                }));
              },
            );
          },
          itemCount: state.chatModelListLen(),
        );
      },
    );
  }
}

class ChatItemWidget extends StatelessWidget {
  final ChatModel chatModel;

  final DayFormat _dayFormat = DayFormat.Simple;

  final VoidCallback onTap;

  const ChatItemWidget({Key key, this.chatModel, this.onTap}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final friend = chatModel.friend;
    final msg = chatModel.message;

    final msgTime = TimelineUtil.format(msg.time.millisecondsSinceEpoch,
        locTimeMillis: DateTime.now().millisecondsSinceEpoch,
        locale: 'zh',
        dayFormat: _dayFormat);

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0, horizontal: 8.0),
      child: Card(
        elevation: 4,
        child: InkWell(
          onTap: onTap,
          child: Container(
            padding: EdgeInsets.all(8.0),
            height: 80.0,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: MyCircleAvatar(
                      height: 40.0, avatar: friend.avatar, tag: friend.id),
                ),
                const SizedBox(width: 4.0),
                Expanded(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        friend.note.isNotEmpty ? friend.note : friend.nickName,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 16.0),
                      ),
                      Text(_getMessageBody(msg),
                          style: const TextStyle(
                              fontSize: 14.0, color: Colors.grey),
                          overflow: TextOverflow.ellipsis),
                    ],
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 8.0),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: <Widget>[
                      Text(
                        msgTime,
                        style: TextStyle(fontSize: 10.0, color: Colors.grey),
                      ),
                      Offstage(
                        offstage: !chatModel.newMessage,
                        child: Container(
                          width: 36.0,
                          height: 16.0,
                          decoration: BoxDecoration(
                            gradient: gradientColor,
                            borderRadius:
                                BorderRadius.all(Radius.circular(25.0)),
                          ),
                          child: Center(
                            child: Text(
                              "NEW",
                              style: TextStyle(
                                  fontSize: 8.0,
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  String _getMessageBody(Message msg) {
    int type = msg.type;
    String body = "暂不支持此消息";

    switch (type) {
      case 0:
        body = msg.body;
        break;

      case 1:
        body = "[语音]";
        break;

      case 2:
        body = "[图片]";
        break;

      case 3:
        body = "[文件]";
    }
    return body;
  }
}
